#include "Image.h"
#include "SDL_rotozoom.h"

ImageMap Image::ms_images;

Image* Image::getImage(uint16_t spriteId)
{
	Image* image = ms_images[spriteId];
	
	if(!image)
	{
		image = new Image();
		image->load(spriteId);
		
		ms_images[spriteId] = image;
	}
	
	return image;
}

Image::Image()
{
	//
}

Image::~Image()
{
	//
}

bool Image::load(const unsigned short& spriteId)
{
	std::stringstream ss;
	ss << spriteId << ".bmp";
	this->load(ss.str().c_str());
	
	printf(SDL_GetError());
	return true;
}

bool Image::load(const std::string& filename)
{
	/* load the space background */
	SDL_Surface* surface = SDL_LoadBMP(filename.c_str());
	if(surface == NULL)
		return false;
		
		
	
	int format = SDL_PIXELFORMAT_ABGR8888;
	Uint32 r, g, b, a;
	int bpp;
	
	SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, 255, 0, 255));
	SDL_PixelFormatEnumToMasks(format, &bpp, &r, &g, &b, &a);
	/*
	for(int x = 0; x < surface->w; x++)
	{
		for(int y = 0; y < surface->h; y++)
		{
			//0,0 ->
			
			/*
			
			0,0 1,0 2,0
			0,1 1,1 2,1
			0,2 1,2 2,2
			
			nX=W-X
			nY=
			
			0,0 -> 2,0 X+2 Y+0
			1,0 -> 2,1 X+1 Y-1
			2,0 -> 2,2 X+0 Y-2
			
			nX=X-Y
			nY=X-Y
			
			0,1 -> 1,0 X+1 Y-1
			1,1 -> 1,1 X+0 Y+0
			2,1 -> 1,2 X-1 Y+1
			
			0,2 -> 0,0
			1,2 -> 0,1
			2,2 -> 0,2
			
			{x,y} -> {y, -x}
		}
	}*/
	
	SDL_Surface* surfaceColor = SDL_CreateRGBSurface(0, surface->w, surface->h, bpp, r, g, b, a);	
//	printf("Surface Color %d %d", surface->w, surface->h);

	SDL_BlitSurface(surface, NULL, surfaceColor, NULL);
	
	/*
	SDL_Surface* rotatedSurface = rotozoomSurface(surfaceColor, -90, 1, 1);
	if(rotatedSurface == 0)
	{
		printf("surface is 0\n");
	}
	
	printf("surface %f %f %d %d\n", rotatedSurface->w, rotatedSurface->h, rotatedSurface->w, rotatedSurface->h);
	 */
	
	/* create space texture from surface */
	m_textureId = SDL_CreateTextureFromSurface(format, surfaceColor);
	if(m_textureId == 0)
	{
		printf("texture id is 0");
		return false;
	}
	
	SDL_SetTextureBlendMode(m_textureId, SDL_TEXTUREBLENDMODE_BLEND);
	
	SDL_FreeSurface(surfaceColor);
	SDL_FreeSurface(surface);
	return true;
}

void Image::draw(SDL_Rect* rect)
{	
	SDL_RenderCopy(m_textureId, NULL, rect);
}
	